
import wx from "weixin-js-sdk"; // 引入微信js-sdk
import { PUBLIC } from "./common-func.js"; // 经常用到的公共方法
import { compressImageByPlugin } from './compress-image.js'
export const UPLOAD = {
  /**
   *
   * @param {*} obj
   * @param type : 传参类型
   * formData内bizClient参数必传
   * count参数默认多图  单图传1
   * compressType 压缩类型 1：ocr相关（人脸，身份证识别、银行卡）2：普通压缩  3: 不压缩
   * @returns
   */
  imgUpload(obj) {
    let ran = navigator.userAgent;
    let isAndroid = ran.indexOf("Android") > -1 || ran.indexOf("Linux") > -1;
    console.log('navigator.userAgent:', navigator.userAgent)
    let isByPluginCompress = true // 是否采用插件的压缩， true为采用插件压缩，false为采用自己写的压缩
    return new Promise((resolve, reject) => {
      const {
        sizeType = ["original", "compressed"],
        sourceType = ["album", "camera"],
        count = 1,
        compressType = 2, // 默认普通压缩
      } = obj;
      let uploadUrl = obj.uploadUrl
      ? obj.uploadUrl
      : window?.LOCAL_CONFIG?.image_service_api
      ? `${window.LOCAL_CONFIG.image_service_api}/file/obs/upload`
      : "/file/obs/upload";
      // 不是微信环境和支付宝环境处理或者安卓手机处理（安卓手机默认使用H5选择图片上传）
      // ios上传微信会压缩，如果需要检测文件大小，走H5上传
      if (!PUBLIC.isWx() || isAndroid) {
        uni.chooseImage({
          count: count, // 默认1
          sizeType: sizeType, // 可以指定是原图还是压缩图，默认二者都有
          sourceType: sourceType, // 可以指定来源是相册还是相机，默认二者都有，在H5浏览器端支持使用 `user` 和 `environment`分别指定为前后摄像头
          success: (res) => {
            console.log(res, "选择的图片");
            // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
            var tempFilePaths = res.tempFilePaths;
            let formData = { bizClient:window?.LOCAL_CONFIG?.head_source , bizCode: new Date().getTime() };
            if (obj.formData) {
              formData = Object.assign(formData, obj.formData);
            }
            let compressedImageList = [];
            let fileLength = res.tempFiles.length;
            uni.showLoading({
              title: "正在上传",
              mask: true,
            });
            res.tempFiles.map((v) => {
              const size = v.originalFileObj.size / 1024 / 1024;
              console.log('size:', size + 'MB')
              // 3 不压缩，1 大于2M压缩，2大于2M压缩
              let needCompress = ((compressType == 1 || compressType == 2) && size > 2)
              compressImageByPlugin(compressType, needCompress, v, size, isByPluginCompress)
                .then(async (compresseResult) => {
                  uni.uploadFile({
                    url: uploadUrl,
                    filePath: compresseResult.path,
                    name: "file",
                    withCredentials: true,
                    formData: formData,
                    fileName: v.originalFileObj.name,
                    header: {
                      "X-Nf-Access-Token": uni.getStorageSync("token") || "",
                      "X-Nf-Source": window?.LOCAL_CONFIG?.head_source || "",
                      "X-Nf-Client-Code":
                        window?.LOCAL_CONFIG?.client_code || "",
                    },
                    success: (uploadFileRes) => {
                      try {
                          let re = JSON.parse(uploadFileRes.data)
                          if(re?.code === 4002){
                            uni.showToast({
                              title: re?.msg || '上传出错啦',
                              icon: "none",
                              duration: 3000
                            });
                            return
                          }
                      } catch (error) {
                        
                      }
                      if(needCompress && isByPluginCompress) {
                        URL.revokeObjectURL(compresseResult.path);
                      }
                      if (count === 1) {
                        uni.hideLoading();
                        let data = JSON.parse(uploadFileRes.data)?.data; //返回处理过的datas
                        resolve(data);
                      } else {
                        uni.hideLoading();
                        compressedImageList.push(uploadFileRes);
                        if (compressedImageList.length == fileLength) {
                          let datas = compressedImageList.length
                            ? compressedImageList.map((v) => {
                                return JSON.parse(v.data)?.data;
                              })
                            : []; //返回处理过的datas
                          resolve(datas);
                        }
                      }
                    },
                    fail: (res) => {
                      reject(res);
                      if (count === 1) {
                        uni.hideLoading();
                      } else {
                        uni.hideLoading();
                        compressedImageList.push(res);
                        // if (compressedImageList.length == fileLength) {
                        // 	resolve(compressedImageList)
                        // }
                      }
                      uni.showToast({
                        icon: "none",
                        title: "出错了",
                      });
                    },
                  });
                })
                .catch((err) => {
                  uni.hideLoading();
                  uni.showToast({
                    icon: "none",
                    title: err && typeof err == 'string' ? err : "图片出错",
                  });
                });
            });
          },
          fail: (res) => {
            console.log(res);
            uni.hideLoading();
            uni.showToast({
              icon: "none",
              title: "选择图片出错",
            });
          },
        });
      } else {
        wx.chooseImage({
          count: count, // 默认1
          sizeType: sizeType, // 可以指定是原图还是压缩图，默认二者都有
          sourceType: sourceType, // 可以指定来源是相册还是相机，默认二者都有
          success: function (res) {
            console.log(res, "选择图片", res.localIds);
            var localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
            // resolve(localIds)

            //上传
            var i = 0;
            var length = localIds.length;
            var serverId = [];
            var upload = function () {
              let loacId = localIds[i];
              console.log("上传第" + i + "张");
              if (!isAndroid) {
                if (loacId.indexOf("wxlocalresource") != -1) {
                  loacId = loacId.replace("wxlocalresource", "wxLocalResource");
                }
              }
              wx.uploadImage({
                localId: loacId.toString(), // 需要上传的图片的本地ID，由chooseImage接口获得
                isShowProgressTips: 1, // 默认为1，显示进度提示
                success: function (res) {
                  console.log(res.serverId);
                  serverId.push(res.serverId); //这里就可以拿到用户上传的所有图片serverId
                  if (serverId.length >= length) {
                    uni.showLoading({
                      title: "加载中",
                    });
                    uni.request({
                      url: window?.LOCAL_CONFIG?.image_service_api
                        ? `${window.LOCAL_CONFIG.image_service_api}/file/obs/wechat/upload`
                        : "/file/obs/wechat/upload",
                      method: "POST",
                      data: {
                        bizClient: obj?.formData?.bizClient || window?.LOCAL_CONFIG?.head_source ,
                        imageType: obj?.formData?.imageType || "",
                        bizCode: obj?.formData?.bizCode ||  new Date().getTime(),
                        mediaIds: serverId,
                      },
                      header: {
                        "X-Nf-Access-Token": uni.getStorageSync("token") || "",
                        "X-Nf-Source": window?.LOCAL_CONFIG?.head_source || '',
                        "X-Nf-Client-Code": window?.LOCAL_CONFIG?.client_code || '',
                      },
                      success: (res) => {
                        uni.hideLoading();
                        if (count === 1) {
                          resolve(
                            res.data?.data.length ? res.data?.data[0] : {}
                          );
                        } else {
                          resolve(res.data?.data);
                        }
                      },
                      fail: async (err) => {
                        uni.hideLoading();
                        uni.showToast({
                          title: err.msg || '上传异常，请刷新页面重试',
                          icon: "none",
                          duration: 3000,
                        });
                        reject(err);
                      },
                      complete: (res) => {
                        uni.hideLoading();
                      },
                    });
                  }
                  i++;
                  i < length && upload();
                },
                fail: function (error) {
                  console.log("uploadImage error", error);
                  uni.showToast({
                    title: error.errMsg,
                    icon: "none",
                    duration: 3000,
                  });
                },
              });
            };
            upload();
          },
          fail: function () {
            // fail
          },
          complete: function () {
            // complete
          },
        });
      }
    });
  },
};
